package com.rmiad.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.noear.snack.ONode;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Get;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.annotation.Post;
import org.noear.solon.cloud.CloudClient;
import org.noear.solon.cloud.model.Media;
import org.noear.solon.core.handle.DownloadedFile;
import org.noear.solon.core.handle.Result;
import org.noear.solon.core.handle.UploadedFile;
import org.noear.solon.validation.annotation.NotBlank;
import org.noear.solon.validation.annotation.NotEmpty;

import java.io.IOException;

/**
 * 上传组件
 *
 * @author wyl
 * @date 2025年05月10日 上午11:32
 */
@Api("上传控制器")
@Controller
public class UploadController {

    @ApiOperation("上传")
    @Post
    @Mapping("/api/upload")
    public Result upload(@NotBlank String bucket, UploadedFile file) throws IOException {
        // 1. 检查文件内容是否为空
        if (file == null || file.getContent() == null) {
            return Result.failure("文件内容为空");
        }

        // 2. 上传到云存储（需确保配置了默认存储桶）
        CloudClient.file().put(bucket, file.getName(), new Media(file.getContent()));

        // 3. 处理上传结果
        ONode a = ONode.newObject()
                .set("filename", file.getName())
                .set("url", "/file/down?bucket=" + bucket + "&key=" + file.getName())
                .set("value", "/file/down?bucket=" + bucket + "&key=" + file.getName());
        return Result.succeed(a);
    }

    @ApiOperation("文件下载或者预览")
    @Get
    @Mapping("/file/down")
    public DownloadedFile down(@NotEmpty String bucket, @NotEmpty String key, boolean attachment) { //表单变量名要跟参数名对上
        Media media = CloudClient.file().get(bucket, key);
        int lastIndexOfSlash = key.lastIndexOf('/'); // 找到最后一个斜杠的位置
        String fileName = key.substring(lastIndexOfSlash + 1); // 从最后一个斜杠后一
        return new DownloadedFile(media.contentType(), media.bodyAsBytes(true), fileName).asAttachment(attachment);
    }

}
